<script lang="ts" setup>
import {
  createEnterpriseAPI,
  editEnterpriseAPI,
  getEnterpriseDetailAPI,
  getIndustryListAPI,
  uploadAPI
} from '@/apis/enterprise';
import type {AddIndustry, Industry, UploadUserFile} from '@/types/enterprise';
import { ElMessage, type FormRules, type UploadFile, type UploadFiles, type UploadRawFile, type UploadRequestOptions } from 'element-plus';
import {computed, onMounted, ref} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {validMobile} from "@/utils/vaildate";

const addForm = ref<AddIndustry>({
  name: '', // 企业名称
  legalPerson: '', // 法人
  registeredAddress: '', // 注册地址
  industryCode: '', // 所在行业
  contact: '', // 企业联系人
  contactNumber: '', // 联系人电话
  businessLicenseUrl: '', // 营业执照url
  businessLicenseId: '' // 营业执照id
})

const addRules = ref<FormRules>({
  name: [
    { required: true, message: '企业名称为必填', trigger: 'blur' }
  ],
  legalPerson: [
    { required: true, message: '法人为必填', trigger: 'blur' }
  ],
  registeredAddress: [
    { required: true, message: '注册地址为必填', trigger: 'blur' }
  ],
  industryCode: [
    { required: true, message: '所在行业为必填', trigger: 'change' }
  ],
  contact: [
    { required: true, message: '企业联系人为必填', trigger: 'blur' }
  ],
  contactNumber: [
    { required: true, message: '企业联系人电话为必填', trigger: 'blur' },
    { validator: validMobile, trigger: 'blur'}
  ],
  businessLicenseId: [
    { required: true, message: '请上传营业执照', trigger: 'blur' }
  ]
})

// 1. 获取企业所属的行业
const industryList = ref<Industry[]>([]) // 可选行业列表
const getIndustryList = async () => {
  const res = await getIndustryListAPI()
  industryList.value = res.data
}
getIndustryList()

// 2. 文件的上传
const fileList = ref<UploadUserFile[]>([])
const uploadRequest = async (options: UploadRequestOptions): Promise<any> =>{
  // 2.1 把文件包装成一个formData对象
  const fd = new FormData()
  fd.append('file', options.file)
  fd.append('type', 'businessLicense')

  // 2.2 调用上传接口函数
  const res = await uploadAPI(fd)
  console.log(res);

  // 2.3 处理给回的数据
  addForm.value.businessLicenseId = res.data.id + ''
  addForm.value.businessLicenseUrl = res.data.url

  fileList.value.push(res.data)

  // 2.4 单独校验表单，清除错误信息
  ruleForm.value.validateField('businessLicenseId')

}

// 3. 删除文件
const onRemove = (uploadFile: UploadFile, uploadFiles: UploadFiles)=>{
  addForm.value.businessLicenseId = ''
  addForm.value.businessLicenseUrl = ''
  fileList.value = []
}

// 4. 上传文件之前校验
const onExceed = ()=>{
  ElMessage({
    message: '只能上传一张营业执照, 请先删除再重新上传',
    type: 'error'
  })
}

const beforeUpload = (rawFile: UploadRawFile)=>{
  // 4.1 校验图片的格式
  const allowImageType = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif'].includes(rawFile.type)
  // 4.2 校验图片大小
  // b -> mb
  const isLt5M = rawFile.size / 1024 / 1024 < 5

  if (!allowImageType) {
    ElMessage.error('上传营业执照图片只能是 PNG/JPG/JPEG/GIF 格式!')
  }
  if (!isLt5M) {
    ElMessage.error('上传营业执照图片大小不能超过 5MB!')
  }

  return allowImageType && isLt5M
}

// 5. 统一进行表单校验
const ruleForm = ref()
const router = useRouter()
const confirmSubmit = () => {
  ruleForm.value.validate(async (valid: boolean) => {
    if (!valid)return
    if(valid){
      // 调用接口
      if (id.value){
      //   编辑
        await editEnterpriseAPI({
          ...addForm.value,
          id: id.value
        })
      }else {
        await createEnterpriseAPI(addForm.value)
      }
      ElMessage({
        message: id? '编辑企业成功' : '添加企业成功',
        type: 'success'
      })
      // 返回列表页
      router.back()
    }
  })
}

// 6. 重置
const reset = ()=>{
  ruleForm.value.resetFields()
}
// 传过来的 企业id
const route = useRoute()
const id = computed(()=>{
  return route.query.id as string
})
const getDetail = async () => {
  const res= await getEnterpriseDetailAPI(id.value)
  const { businessLicenseId, businessLicenseUrl, contact, contactNumber, industryCode, legalPerson, name, registeredAddress, businessLicenseName } = res.data
  addForm.value={ businessLicenseId, businessLicenseUrl, contact, contactNumber, industryCode, legalPerson, name, registeredAddress }
  fileList.value.push({
    name: businessLicenseName,
    url: businessLicenseUrl,
    id: businessLicenseId,
  })
}
onMounted(()=>{
  if (id.value) {
    getDetail()
  }
})
</script>


<template>
  <div class="add-enterprise">
    <header class="add-header">
      <el-page-header :content=" id ? '编辑企业' : '添加企业'" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="ruleForm" :model="addForm" :rules="addRules" label-width="100px">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode">
                <el-option v-for="item in industryList" :key="item.industryCode" :label="item.industryName"
                           :value="item.industryCode"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseId">
              <el-upload :before-upload="beforeUpload" :file-list="fileList" :http-request="uploadRequest" :limit="1"
                         :on-exceed="onExceed" :on-remove="onRemove" action="#" list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">支持扩展名：.png .jpg .jpeg, 文件大小不得超过5M</div>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="reset">重置</el-button>
        <el-button type="primary" @click="confirmSubmit">确定</el-button>
      </div>
    </footer>
  </div>
</template>


<style lang="scss" scoped>
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>